package main

import (
	"fmt"
	"os"
	"path/filepath"
)

func factorial(n int) int {
	if n == 0 {
		return 1
	}
	return n * factorial(n-1)
}

func fibonacci(n int) int {
	if n < 2 {
		return n
	}

	return fibonacci(n-2) + fibonacci(n-1)
}

func main() {

	fmt.Println(factorial(5))

	// 斐波那契数列
	var i int
	for i = 0; i < 10; i++ {
		fmt.Printf("%d\t", fibonacci(i))
	}

	//求平方根

	x := 25.0
	result := sqrt(x)

	fmt.Printf("%.2f 的平方根为 %.6f \n", x, result)

	walkDir(".", "")
}

func sqrtRecursive(x, guess, prevGuess, epsilon float64) float64 {
	if diff := guess*guess - x; diff < epsilon && -diff < epsilon {
		return guess
	}

	newGuess := (guess + x/guess) / 2
	if newGuess == prevGuess {
		return guess
	}

	return sqrtRecursive(x, newGuess, guess, epsilon)
}

func sqrt(x float64) float64 {
	return sqrtRecursive(x, 1.0, 0.0, 1e-9)
}

func walkDir(dir string, indent string) {
	entries, err := os.ReadDir(dir)
	if err != nil {
		return
	}

	for _, entry := range entries {
		fmt.Println(indent + entry.Name())
		if entry.IsDir() {
			walkDir(filepath.Join(dir, entry.Name()), indent+" ")
		}
	}
}
